package leetcode;

public class LeetCode75 {

    public void sortColors1(int[] nums) {
        for (int i = 0; i < 3; i++) {
            swap(i, nums);
        }
    }

    private void swap(int target, int[] nums) {
        //双指针  指针p指向可以存放的第一个位置  指针q指向当前位置
        int p = 0, q = 0, tmp;
        while (p < nums.length && nums[p] < target) {
            p++;
        }
        q = p;
        for (int i = q; i < nums.length; i++) {
            if (nums[q] == target) {
                tmp = nums[q];
                nums[q] = nums[p];
                nums[p] = tmp;
                p++;
            }
        }
    }
//------------------------------------------------------------------

    //一次遍历，双指针法
    public void sortColors2(int[] nums) {
        int p = 0, q = nums.length - 1;
        while (nums[p] == 0)
            p++;
        while (nums[q] == 2)
            q--;
        for (int i = p; i <= q; i++) {
            if (nums[i] == 0) {
                swap(p, i, nums);
                p++;
            } else if (nums[i] == 2) {
                swap(q, i, nums);
                q--;
            }

        }
    }

    private void swap(int i, int j, int[] nums) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public void sortColors(int[] nums) {
        // 对于所有 idx < i : nums[idx < i] = 0
        // j是当前考虑元素的下标
        int p0 = 0, curr = 0;
        // 对于所有 idx > k : nums[idx > k] = 2
        int p2 = nums.length - 1;

        int tmp;
        while (curr <= p2) {
            if (nums[curr] == 0) {
                // 交换第 p0个和第curr个元素
                // i++，j++
                tmp = nums[p0];
                nums[p0++] = nums[curr];
                nums[curr++] = tmp;
            }
            else if (nums[curr] == 2) {
                // 交换第k个和第curr个元素
                // p2--
                tmp = nums[curr];
                nums[curr] = nums[p2];
                nums[p2--] = tmp;
            }
            else curr++;
        }
    }
}
